<template>
  <div>
    <el-card class="mb">
      <div class="title mb">指标管理</div>
      <el-form :inline="true" label-width="100px">
        <el-form-item label="指标名称：">
          <el-input
            v-model="form.indexName"
            placeholder="选输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker
            v-model="form.createTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button
        type="primary"
        @click="addEditOpen"
        icon="el-icon-plus"
        class="mb"
        v-if="!onlyLook"
        >新建</el-button
      >
      <el-tabs v-model="activeName" @tab-click="getListData">
        <el-tab-pane
          v-for="(pageData, index) in allPagesArr"
          :key="pageData.tabNameLabel"
          :label="pageData.tabNameLabel"
          v-model="activeName"
          :name="index + ''"
        >
          <Table
            @handleSizeChange="
              (v) => {
                handleSizeChange(v, index)
              }
            "
            @handleCurrentChange="
              (v) => {
                handleCurrentChange(v, index)
              }
            "
            :pageSize="pageData.pageSize"
            :current="pageData.pageNum"
            :total="pageData.total"
            :tableData="pageData.tableData"
            :tabtitle="tabTitle"
            :loading="loading"
            height="calc(100vh - 400px)"
          >
            <el-table-column align="center" label="操作" v-if="!onlyLook">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="addEditOpen(scope.row)"
                  class="blueBtn"
                  >编辑</el-button
                >

                <el-button
                  type="text"
                  :disabled="scope.row.type != '0'"
                  @click="deleteData(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </Table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <AddEdit ref="addEdit"></AddEdit>
  </div>
</template>

<script>
import AddEdit from './components/AddEdit.vue'
import Table from '@/components/Table.vue'
import { list, del } from '@/apis/indexManagement.js'
import { getDetailByAccountOrId, getUserInfo, getSelf } from '@/apis/Common.js'
import { getRealToken } from '@/utils/util'

export default {
  components: {
    Table,
    AddEdit
  },
  data() {
    return {
      form: {
        indexName: '',
        createTime: ''
      },

      activeName: '0',
      onlyLook: false,
      allPagesArr: [
        {
          tabName: `全部指标`,
          tabNameLabel: '全部指标',
          tableData: [],
          pageSize: 10,
          current: 1,
          total: 0
        },
        {
          tabName: `手工录入`,
          tabNameLabel: '手工录入',
          tableData: [],
          pageSize: 10,
          pageNum: 1,
          total: 0
        },
        {
          tabName: `数据读取`,
          tabNameLabel: '数据读取',
          tableData: [],
          pageSize: 10,
          pageNum: 1,
          total: 0
        }
      ],

      loading: false,

      tabTitle: [
        { prop: 'indexName', label: '指标名称' },
        { prop: 'tableFrom', label: '来源表' },
        { prop: 'formula', label: '公式' },
        { prop: 'describe', label: '描述' },
        { prop: 'userName', label: '填报人' },
        {
          prop: 'dataFrom',
          label: '数据来源',
          render: (h, scope) => {
            return h('div', scope.row.dataFromDes)
          }
        },
        {
          prop: 'updateTime',
          label: '更新频率'
        },
        { prop: 'createTime', label: '创建时间', sortable: true },
        {
          prop: 'type',
          label: '状态',
          render: (h, scope) => {
            return h(
              'div',
              {
                attrs: {
                  class: scope.row.type
                    ? scope.row.type === '0'
                      ? 'type-normal'
                      : 'type-success'
                    : ''
                }
              },
              scope.row.typeDes
            )
          }
        }
      ]
    }
  },
  mounted() {
    this.getListData()
    this.getUserRole()
  },
  methods: {
    async getUserRole() {
      try {
        const accessObj = getRealToken()
        const isCheckOut = accessObj?.isCheckOut
        let res = null
        if (isCheckOut) {
          const resInfo = await getSelf()
          res = await getUserInfo(resInfo.tenantId)
        } else {
          res = await getDetailByAccountOrId({
            account: sessionStorage.getItem('currentUser')
              ? JSON.parse(sessionStorage.getItem('currentUser')).account
              : null
          })
        }
        if (res?.role?.roleCode?.length > 0) {
          const roleCode = res.role.roleCode.split('|')
          const arr = roleCode
            .map((roleCode) =>
              ['hygczmkcy-gcy', 'hygczmkjt-gcy'].indexOf(roleCode)
            )
            .filter((index) => index !== -1)
          if (arr.length > 0) {
            this.onlyLook = true
          } else {
            this.onlyLook = false
          }
        } else {
          this.onlyLook = true
        }
      } catch (error) {
        this.onlyLook = true
      }
    },
    getListData() {
      this.allPagesArr.forEach((e, i) => {
        this.getList(i)
      })
    },

    deleteData(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row.id).then((res) => {
            if (res.code === 200) {
              this.getListData()
              this.$message.success('删除成功')
              // this.addLog(0, 'del', {
              //   id: row.id
              // }, 'success')
            } else {
              // this.addLog(0, 'del', {
              //   id: row.id
              // }, 'error')
              this.$message.warning(res.data || '删除失败!')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    getList(type) {
      this.loading = true
      list({
        ...this.form,
        pageSize: this.allPagesArr[type].pageSize,
        pageNum: this.allPagesArr[type].pageNum,
        dataFrom: type == 0 ? '' : type
      })
        .then((res) => {
          if (res.code === 200) {
            let { total, list } = res.data
            this.allPagesArr[type] = {
              ...this.allPagesArr[type],
              total,
              tableData: list || [],
              tabNameLabel: `${this.allPagesArr[type].tabName}(${total})`
            }
            this.$forceUpdate()
          } else {
            this.allPagesArr[type] = {
              ...this.allPagesArr[type],
              total: 0,
              tableData: [],
              tabNameLabel: `${this.allPagesArr[type].tabName}(${0})`
            }
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    search() {
      this.allPagesArr = this.$options.data().allPagesArr

      this.getListData()
    },

    reset() {
      this.form = this.$options.data().form
      this.allPagesArr = this.$options.data().allPagesArr
      this.getListData()
    },

    addEditOpen(row) {
      this.$refs.addEdit.show(row)
    },

    handleSizeChange(val, index) {
      this.allPagesArr[index].pageSize = val
      this.getList(index)
    },
    handleCurrentChange(val, index) {
      this.allPagesArr[index].current = val
      this.getList(index)
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  font-size: 20px;
  font-weight: bold;
}
.mb {
  margin-bottom: 20px;
}
.disf {
  display: flex;
  align-items: center;
}
/deep/.el-tabs__item.is-top {
  font-size: 16px;
}
/deep/.selectRow {
  background: #e1f7ff;
  padding: 0 40px;
  margin-bottom: 10px;
  border: 1px solid #d8f1fa;
  div:nth-child(1) {
    width: 110px;
    border-right: 1px solid #1890ff;
    margin-right: 10px;
    span {
      margin: 0 5px;
      color: #1890ff;
    }
  }
  .el-button {
    width: 80px;
    color: #1890ff;
    border: none;
    background: #e1f7ff;
  }
}
.btnStyle {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.15294117647058825);
}
.blueBtn {
  color: #1890ff;
}
</style>
